/**
 * 开票通知 - 编辑页面
 * @author liuw
 * @date 2019/09/04
 */
define(function () {

    var self,
        app = win.app,
        doc = document,
        layui = win.layui,
        vueData = {
            isAdd: false,
            form: {
                GWED001_NAME:null,
                GWED004_NAME:null,
                GWED101_NAME:null,
                GWEDMLEGAL_NAME:null,
                GWEDPLANT_NAME:null
            },
            digit: {
                price: 100,
                amount: 100
            },
            total: {
                rows: 0,
                num:0,
                sum:0
            },
            rules: {
                GWEDDOCNO: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ],
                GWEDDOCDATE: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ],
                GWED004: [
                    {required: true, message: '不可为空', trigger: 'change'}
                ],
                GWED004_NAME: [
                    {required: true, message: '不可为空', trigger: 'change'}
                ],
                GWED002: [
                    {required: true, message: '不可为空', trigger: 'change'}
                ],
                GWEDMLEGAL: [
                    {required: true, message: '不可为空', trigger: 'change'}
                ]
            },
            selectOptions: {
                optionsGwed002: app.datas_('crm_gwei006_gwed002')
            },
        },
        cols = [[
            {type:'checkbox',fixed: 'left'},
            { field: "GWEDDOCNO", title: "申请单号", width: 150},
            { field : "GWEDSEQ" , title: "项次", width : 50},
            { field: "GWEDDOCDATE", title: "申请日期", width: 100,sort:true},
            { field: "GWED001", title: "申请人编号", hide:true},
            { field: "GWED001_NAME", title: "申请人", width: 100},
            { field: "GWED003", title: "出货单号", width: 180},
            { field: "GWED102", title: "出货单项次", width: 130},
            { field: "GWED004_NAME", title: "客户", width: 100},
            { field : "GWED008" , title: "产品编号", width : 100},
            { field : "GWAML003" , title: "品名", width : 150},
            { field : "GWAML004" , title: "规格", width : 100},
            { field : "GWED009" , title: "数量", width : 100,edit:'text',sort:true},
            { field : "GWED010" , title: "单价", width : 100,edit:'text',sort:true},
            { field : "GWED011" , title: "金额", width : 100,edit:'text',sort:true},
            { field : "GWED002" , title: "发票种类", width : 100,filterDatas: app.datas_('crm_gwei006_gwed002')},
            { field : "GWED101" , title: "归属组织编号", hide: true},
            { field : "GWED101_NAME" , title: "归属组织", width : 100},
            { field : "GWED013" , title: "备注", width : 100},
            { field : "GWEDACTI" , title: "有效否", width : 100,filterDatas: app.datas_('sys_y_n')},
            { field : "GWED004" , title: "客户编号",hide: true},
            { field : "SUM_NUM" , title: "-",hide: true},
        ]],
        callObj,
        listData = null,
        pageVue,

        table, gwei006EditTable,layOpenIndex
    ;

    var Gwei006Edit = app.Module.extend({
        init: function () {
                self = this;
                self._super({
                    _tag: 'gwei006_edit',
                    _loadTplsFull: [{
                        dom: 'common_open_window', tpl: 'common/_open_window'
                    },{
                        dom: 'gwei006_edit_add', tpl: 'gwei006_edit_add'
                    }]
                }, win);
            },

        initTable: function () {
                layui.use(['table'], function () {
                    table = layui.table;
                    gwei006EditTable = table.render({
                        elem: app.getByid(doc, 'gwei006_edit_table'),
                        id: 'gwei006_edit_table',
                        height:'240',
                        cols: cols,
                        data: listData
                    });

                });
                table.on('edit(gwei006_edit_table)', function(obj){
                    var oldValue = $(this).prev().text();

                    self.numFormatBeforeCalulate(obj.data);

                    if (obj.field === 'GWED009') {
                        self.onGwed009Change(obj,oldValue);
                    } else {
                        var checkResult = self.checkMoney(obj,oldValue);
                        if(!checkResult) return;

                        if(obj.field === 'GWED010'){
                            self.onGwed010Change(obj);
                        }
                    }

                    self.numFormatAfterCalulate(obj.data);
                    obj.updateOfEdit({
                        GWED009: obj.data.GWED009 ,
                        GWED010: obj.data.GWED010 ,
                        GWED011: obj.data.GWED011
                    });
                    self.calTotal(gwei006EditTable.getDatas());
                });
            },

        numFormatUtil: function(num ,digit) {
            return math.div(Math.round(math.mul(num,digit)) ,digit);
        },

        numFormatBeforeCalulate: function(data){
                data.GWED009 = parseInt(data.GWED009);
                data.GWED010 = parseFloat(data.GWED010);
                data.GWED011 = parseFloat(data.GWED011);
            },

        numFormatAfterCalulate: function(data){
                var price = vueData.digit.price;
                var amount = vueData.digit.amount;
                data.GWED010 = self.numFormatUtil(data.GWED010,price);
                data.GWED011 = self.numFormatUtil(data.GWED011,amount);
            },

        calTotal:function(data) {
                var _total = {
                    rows: data.length,
                    num: 0,
                    sum:0
                };
                data.forEach(function (v) {
                    _total.num = math.add(_total.num,v.GWED009);
                    _total.sum = math.add(_total.sum,v.GWED011);
                });
                app.extendUpLow({
                    target: vueData.total,
                    res:_total,
                    reset: true
                })
            },

        checkMoney: function(obj,oldValue) {
                var flag = true;
                var re = /^[0-9]+.?[0-9]*$/;

                var field = obj.field;
                var title='';
                var _cols = cols[0];
                for(var i=0;i<_cols.length;i++) {
                    if(_cols[i].field === field) {
                        title = _cols[i].title;
                        break;
                    }
                }

                if((!re.test(obj.value)) || parseFloat(obj.value) <= 0 ){
                    obj[field] = oldValue;

                    obj.updateOfEdit({
                        [field]: obj[field]
                    });
                    app.showWarning(title + "应为数字类型！");
                    flag = false;
                    return flag;
                }
                obj[field] = obj.value;

                return flag;
            },

        onGwed009Change: function(obj,oldValue) {
                var data = obj.data;
                var re = /^[0-9]*$/; //判断是否正整数
                if((!re.test(obj.value)) || parseFloat(obj.value) <= 0 ){
                    data.GWED009 = oldValue;
                    obj.updateOfEdit({
                        GWED009: oldValue
                    });
                    app.showWarning("数量为应为正整数！");
                    return;
                } else {
                    var gwed009_sum = parseFloat(obj.data.SUM_NUM); // 出货数量（可开票数量）
                    var gwed009 = parseFloat(obj.value);
                    if(gwed009 > gwed009_sum) {
                        data.GWED009 = oldValue;
                        obj.updateOfEdit({
                            GWED009: oldValue
                        });
                        app.showWarning("本次开票数量不能大于可申请发票数量！(" + gwed009_sum + ")");
                    }
                }

                var GWED009 = obj.data.GWED009;
                data.GWED011 = math.mul(data["GWED010"] , GWED009);
            },

        onGwed010Change: function(obj) {
                var data = obj.data;
                var GWED010 = data.GWED010;
                data.GWED011 = math.mul(GWED010 , data["GWED009"]);
            },

        tableReload: function (listData) {
                self._reloadTable({id: 'gwei006_edit_table', data: listData});
            },

        addData: function (listData) {
                app.ajax({
                    xurl: 'crm/gwei006/addData',
                    xdata: listData,
                    loading: true,
                    toJsonStr: true,
                    okmsg: '开票通知增加成功',
                    cb: function (result) {
                        if (result.ok) {
                            app.pageModule('gwei006').reloadTableCurr();
                            self._closeTpl();
                        }
                    }
                });
            },

        editData: function (listData) {
                app.ajax({
                    xurl: 'crm/gwei006/editData',
                    xdata: listData,
                    loading: true,
                    toJsonStr: true,
                    okmsg: '开票通知修改成功',
                    cb: function (result) {
                        if (result.ok) {
                            app.pageModule('gwei006').reloadTableCurr();
                            self._closeTpl();
                        }
                    }
                });
            },

        getDigit:function() {
            app.ajax({
                xurl: 'admin/getDigit',
                async: true,
                cb: function (result) {
                    if(result.ok) {
                        var data = result.data.data;
                        var _digit = {
                            price: Math.pow(10,data.price),
                            amount: Math.pow(10,data.amount),

                        }
                        app.extendUpLow({
                            target: vueData.digit,
                            res: _digit,
                            reset: true
                        })
                    }else {
                        console.log("获取小数位失败");
                    }
                }
            });
        },

        doOpenGwakPge:function() {
            self._openTplFull({
                tag: 'common_open_window',
                tagData: {
                    config: {
                        method:'cq_gwak001_1',
                        columnList: [
                            {label:'客户编号',prop:'GWAK001', width: 150},
                            {label:'客户简称',prop:'GWAKL003', width: 150},
                            {label:'客户全称',prop:'GWAKL004', width: 150}
                        ],
                    },
                    cb: function (data) {
                        vueData.form.GWED004 = data.GWAK001;
                        vueData.form.GWED004_NAME = data.GWAKL003;
                    }
                },
                index: 0,
                openOpts: {
                    title: '选择客户',
                    area: ['600px', '465px']
                }
            });
        },

        _call: function (tagData) {
            pageVue.$refs.form.resetFields();
            layOpenIndex = tagData.layOpenIndex;
            if (tagData.is_add) {
                vueData.isAdd = true;
                app.ajax({
                    xurl: 'crm/gwei006/getAddData',
                    cb: function (result) {
                        if (result.ok) {
                            var resData = result.data.data;
                            app.extendUpLow({
                                target: vueData.form,
                                res: {
                                    GWEDDOCNO: resData.GWEDDOCNO,
                                    GWED001:resData.GWED001,
                                    GWED001_NAME:resData.GWED001_NAME,
                                    GWED101:resData.GWED101,
                                    GWED101_NAME : resData.GWED101_NAME,
                                    GWEDDOCDATE: new Date().Format("yyyy-MM-dd")
                                },
                                reset: true
                            });

                            listData = [];
                            self.tableReload(listData);
                            self.calTotal(listData);
                        }
                    }
                });
            } else {
                vueData.isAdd = false;
                callObj = tagData.obj;
                app.ajax({
                    xurl: 'crm/gwei006/getDetailList',
                    xdata: {GWEDDOCNO: callObj.data.GWEDDOCNO},
                    loading: true,
                    cb: function (result) {
                        if(result.ok) {
                            app.extendUpLow({
                                target: vueData.form,
                                res: callObj.data,
                                reset: true
                            });

                            listData = result.data.data;
                            vueData.form.GWED101 = listData[0].GWED101;
                            vueData.form.GWED101_NAME = listData[0].GWED101_NAME;
                            vueData.form.GWEDMLEGAL = listData[0].GWEDMLEGAL;
                            vueData.form.GWEDMLEGAL_NAME = listData[0].GWEDMLEGAL_NAME;
                            vueData.form.GWEDPLANT = listData[0].GWEDPLANT;
                            vueData.form.GWEDPLANT_NAME = listData[0].GWEDPLANT_NAME;
                            self.tableReload(listData);
                            self.calTotal(listData);

                        }
                    }
                });
            }


        },

        _ready: function () {
            table = layui.table;
            vueData.form = app.fields_(['GWED_T'],vueData.form);
            pageVue = new Vue({
                el: '#gwei006_edit',
                data: vueData,
                watch: {
                    'form.GWED001': function () {
                        app.ajax({
                            xurl: 'crm/gwei006/getGwed101',
                            xdata: {GWED001: vueData.form.GWED001},
                            loading: true,
                            cb: function (result) {
                                if (result.ok) {
                                    vueData.form.GWED101 = result.data.data.GWED101;
                                    vueData.form.GWED101_NAME = result.data.data.GWED101_NAME;
                                }
                            }
                        });
                    },
                    'form.GWED101': function () {
                        var list = gwei006EditTable.getDatas();
                        for (var i = 0; i < list.length; i++) {
                            list[i].GWED101 = vueData.form.GWED101;
                            list[i].GWED101_NAME = vueData.form.GWED101_NAME;
                        }
                        table.reload('gwei006_edit_table', {
                            data: list
                        });
                    }
                },
                methods: {
                    cancle: function () {
                        self._closeTpl();
                    },
                    saveData: function () {
                        this.$refs['form'].validate(function (valid) {
                            if (valid) {
                                var listData = gwei006EditTable.getDatas();
                                if(listData.length == 0){
                                    app.showWarning('表格不能为空!');
                                    return;
                                }
                                for (var i = 0; i < listData.length; i++) {
                                    var v = listData[i];
                                    if (v.GWED009 <= 0) {
                                        app.showWarning('存在产品数量不大于0的数据，请修改!');
                                        return;
                                    }
                                }
                                listData.addMap({
                                    GWEDDOCDATE: vueData.form.GWEDDOCDATE,
                                    GWED001: vueData.form.GWED001,
                                    GWED002: vueData.form.GWED002,
                                    GWED101: vueData.form.GWED101,
                                    GWEDMLEGAL : vueData.form.GWEDMLEGAL,
                                    GWEDPLANT: vueData.form.GWEDPLANT,
                                    GWED013: vueData.form.GWED013,
                                    GWEDCONF: vueData.form.GWEDCONF
                                },true);
                                if (vueData.isAdd) {
                                    self.addData(listData);
                                } else {
                                    self.editData(listData);
                                }
                            }
                        });
                    },

                    addData: function () {
                        var formData = vueData.form;
                        var listData = gwei006EditTable.getDatas();
                        if (formData.GWED004_NAME == null) {
                            app.showWarning('请先选择客户');
                            return;
                        }
                        // if (vueData.form.GWEDMLEGAL_NAME == null) {
                        //     app.showWarning('请先选择归属法人');
                        //     return;
                        // }
                        var gweclist = [];
                        listData.forEach(function (v) {
                            gweclist.push(v.GWED003 + v.GWED102);
                        });
                        formData.gweclist = gweclist.join(",");
                        self._openTplFull({
                            tag: 'gwei006_edit_add',
                            tagData: {
                                obj: formData,
                                cb : function (data) {
                                    var tableData = gwei006EditTable.getDatas();
                                    var length = tableData.length;
                                    var num = 0;
                                    if (length !== 0) {
                                        num = parseInt(tableData[length - 1].GWEDSEQ);
                                    }
                                    for (let i = 0; i < data.length; i++) {
                                        var GWED009 = math.sub(data[i]["GWEC009"] , data[i]["GWED009_SUM"]);
                                        let temp = {
                                            GWEC014 : data[i].GWEC014,
                                            GWEC013 : data[i].GWEC013,
                                            GWEDSEQ : num + (i + 1) ,
                                            GWED008 : data[i].GWEC004,
                                            GWAML003 : data[i].GWAML003,
                                            GWAML004 : data[i].GWAML004,
                                            GWED004: data[i].GWEC005,
                                            GWED004_NAME: data[i].GWAKL003,
                                            GWED009 : GWED009,
                                            GWED010 : data[i].GWAP100 ,
                                            GWED011 : math.mul(GWED009 , data[i]["GWAP100"]) ,
                                            GWED003 : data[i].GWECDOCNO ,
                                            GWED102 : data[i].GWECSEQ ,
                                            SUM_NUM : GWED009
                                        };

                                        self.numFormatAfterCalulate(temp);
                                        listData.push(temp);
                                    }
                                    listData.addMap({
                                        GWEDDOCNO: vueData.form.GWEDDOCNO,
                                        GWEDDOCDATE: vueData.form.GWEDDOCDATE,
                                        GWED001: vueData.form.GWED001,
                                        GWED001_NAME: vueData.form.GWED001_NAME,
                                        GWED013: vueData.form.GWED013,
                                        GWED002: vueData.form.GWED002,
                                        GWED101: vueData.form.GWED101,
                                        GWED101_NAME: vueData.form.GWED101_NAME,
                                        GWEDPLANT: vueData.form.GWEDPLANT,
                                        GWEDACTI: 'Y',
                                    })
                                    self.tableReload(listData);
                                    self.calTotal(listData);
                                }
                            },
                            index: 1,
                            openOpts: {
                                title: '选择出货单',
                                area: ['1000px', '500px']
                            }
                        });
                    },

                    del: function () {
                        var list = gwei006EditTable.getDatas();
                        var checkStatus = table.checkStatus('gwei006_edit_table');
                        if (checkStatus.data.length > 0) {
                            checkStatus.data.forEach(function (v) {
                                list.removeByMap({
                                    GWEDSEQ: v.GWEDSEQ
                                });
                            });
                            if (list.length != 0) {
                                var i = 1;
                                list.forEach(function (v) {
                                    v.GWEDSEQ = i;
                                    i++;
                                });
                            }
                            self.calTotal(list);
                            self.tableReload(list);
                        } else {
                            app.showWarning("至少选择一笔数据进行操作")
                        }
                    },

                    // 客户开窗
                    openGwakPage:function () {
                        var listData = gwei006EditTable.getDatas();
                        // 客户不为空
                        if (vueData.form.GWED004 != '' && vueData.form.GWED004 != null) {
                            if(listData.length > 0){
                                app.confirm({
                                    msg: '修改客户将清空表格信息，是否确认修改？',
                                    ok: function () {
                                        listData = [];

                                        self.tableReload(listData);
                                        self.calTotal(listData);
                                        self.doOpenGwakPge();
                                    }
                                });
                            }else {
                                self.doOpenGwakPge();
                            }
                        }else {
                           self.doOpenGwakPge();
                        }

                    },

                    // 组织开窗
                    openGwed101:function () {
                        self._openTplFull({
                            tag: 'common_open_window',
                            tagData: {
                                config: {
                                    method:'q_sysorg_id',
                                    columnList: [
                                        {label: '组织编号', prop: 'ID', width: '150'},
                                        {label: '组织名称', prop: 'NAME', width: '150'}
                                    ],
                                },
                                cb: function (data) {
                                    vueData.form.GWED101 = data.ID;
                                    vueData.form.GWED101_NAME = data.NAME;
                                }
                            },
                            index: 0,
                            openOpts: {
                                title: '选择归属组织信息',
                                area: ['600px', '465px']
                            }
                        });
                    },

                    // 归属法人以及营运中心开窗
                    openGwedmlegal:function () {
                        self._openTplFull({
                            tag: 'common_open_window',
                            tagData: {
                                config: {
                                    method: 'cq_sysorg_biz_1',
                                    columnList: [
                                        {label: 'ID', prop: 'ID', width: '150'},
                                        {label: '归属法人', prop: 'NAME', width: '150'},
                                        {label: '营运中心编号', prop: 'AZP01', width: '150',sortable:false,unshow:true},
                                        {label: '营运中心名称', prop: 'AZP02', width: '150',sortable:false,unshow:true}
                                    ],
                                },
                                cb: function (data) {
                                    vueData.form.GWEDMLEGAL = data.ID;
                                    vueData.form.GWEDMLEGAL_NAME = data.NAME;
                                    vueData.form.GWEDPLANT = data.AZP01;
                                    vueData.form.GWEDPLANT_NAME = data.AZP02;
                                },
                            },
                            index: 0,
                            openOpts: {
                                title: '选择归属法人',
                                area: ['700px', '465px']
                            }
                        });
                    },

                    // 申请人员开窗 （引用销售人员开窗）
                    openGwed001: function () {
                        self._openTplFull({
                            tag: 'common_open_window',
                            tagData: {
                                config: {
                                    method:'q_sysuser_id',
                                    columnList: [
                                        {label: '申请人员编号', prop: 'ID', width: '150'},
                                        {label: '申请人员名称', prop: 'NAME', width: '150'}
                                    ],
                                },
                                cb: function (data) {
                                    vueData.form.GWED001 = data.ID;
                                    vueData.form.GWED001_NAME = data.NAME;
                                }
                            },
                            index: 0,
                            openOpts: {
                                title: '选择申请人员',
                                area: ['600px', '465px']
                            }
                        });
                    },
                    clearMlgeal:function () {
                        if(vueData.form.GWEDMLEGAL_NAME == '' || vueData.form.GWEDMLEGAL_NAME == null){
                            vueData.form.GWEDPLANT = '';
                            vueData.form.GWEDPLANT_NAME = '';
                        }
                    },
                    clearGwed001:function() {
                        vueData.form.GWED001 = "";
                        vueData.form.GWED001_NAME = "";
                    },
                    clearGwed004:function() {
                        vueData.form.GWED004 = "";
                        vueData.form.GWED004_NAME = "";
                    },
                    clearGwed101:function() {
                        vueData.form.GWED101 = "";
                        vueData.form.GWED101_NAME = "";
                    }

                },
                created: function () {
                    self._setEleIsReady('gwei006_edit');
                }
            });
            self.initTable();
        },
        _lazy: function () {
            this._super();
            this.getDigit();
        }
    });

    return new Gwei006Edit();

})
;